/*
  spr-sdk: Statistical Pattern Recognition SDK
  Copyright (C) 2010 Marco Ambu

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef _PR_TRAININGSETREADER_H
#define	_PR_TRAININGSETREADER_H

#include "pr/TrainingSet.h"
#include "pr/PatternReader.h"
#include "util/Image.h"
#include <istream>
#include <fstream>

namespace pr {

class TrainingSet;

class TrainingSetReader
{

  class PatternInfo
  {
  public:
    PatternInfo(const std::string url, std::size_t classId, const std::string& resourceType)
      : Url(url)
      , ClassId(classId)
      , ResourceType(resourceType)
    {}

    std::string Url;
    std::size_t ClassId;
    std::string ResourceType;
  };

  class TrainingSetConfig
  {
  public:
    std::size_t size() const { return patternConfig_.size(); }

    void addPattern(const std::string& url, std::size_t classId, const std::string& resourceType)
    {
      patternConfig_.push_back(PatternInfo(url, classId, resourceType));
    }

    const PatternInfo& getPattern(std::size_t index) const
    {
      return patternConfig_[index];
    }

    std::vector<PatternInfo> patternConfig_;
    std::string urlBase_;
  };

public:
  TrainingSetReader(TrainingSet& trainingSet);

  void readConfigFromFile(const std::string& configFilename);

  void addPattern(const std::string& url, std::size_t classId, const std::string& resourceType = "");

  template <typename PatternReader>
  void read(const PatternReader& reader);

private:
  TrainingSetConfig config_;
  TrainingSet& trainingSet_;
};

template <typename Reader>
void TrainingSetReader::read(const Reader& reader)
{
  for (std::size_t i = 0; i < config_.size(); ++i)
  {
    const PatternInfo& patternInfo = config_.getPattern(i);
    std::ifstream is(patternInfo.Url.c_str());
    trainingSet_.add(reader.fromStream(is), patternInfo.ClassId);
    is.close();
  }
}

} // namespace pr

#endif	// _PR_TRAININGSETREADER_H
